import { loadingManager } from '@/utils/loading'
// 预加载函数
export const preloadImages = (imagesToLoad) => {
  const imageLoadPromises = []
  const imageObjects = {}
  let count = 0

  Object.entries(imagesToLoad).forEach(([key, url]) => {
    const imgPromise = new Promise((resolve, reject) => {
      const img = new Image()
      img.src = url
      imageObjects[key] = url
      img.onload = () => {
        count++
        const width = Math.floor((count * 100) / Object.keys(imagesToLoad).length)
        loadingManager.progressBar.style.width = width + '%'
        loadingManager.progressNum.innerHTML = width + '%'
        resolve()
      }
      img.onerror = () => reject()
    })
    imageLoadPromises.push(imgPromise)
  })
  return { imageLoadPromises, imageObjects }
}

// 转化百分比
/**
 * @param {需要转化为百分比的小数} decimalStr
 * @returns
 */
export const toIntegerPercentage = (decimalStr) => {
  // 乘以100并四舍五入后拼接百分号
  return Math.round(decimalStr * 100) + '%'
}
